<template>
    <div class="adjust_from">
        <!-- 编辑分组dialog -->
        <el-dialog title="新建分组" :visible.sync="dialogVisible" :width="groupDialogWidth" :destroy-on-close="true"
            :close-on-click-modal="false" :close-on-press-escape="false" v-dialogDrag>
            <div class="dialog_content">
                <el-form :model="ruleForm" ref="ruleForm" label-width="120px" class="demo-ruleForm" label-position="left"
                    :rules="rules">
                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="添加分组名称" prop="groupTool" class="group_item">
                                <el-input placeholder="请输入内容" v-model.trim="ruleForm.groupTool" class="input-with-select">
                                    <el-button slot="append" icon="el-icon-plus"
                                        :disabled="isDisabled || !Boolean(ruleForm.groupTool)"
                                        @click="addGroup"></el-button>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2">
                            <el-popover placement="right" width="350" trigger="hover">
                                <div class="popover_content">
                                    <div>·必须以字母开头，支持字母，数字，中、下划线；</div>
                                    <div>·不能包含空格特殊字符；</div>
                                    <div>·最后一个字符不能为下划线或中划线；</div>
                                    <div>·长度为1-8个字符；</div>
                                </div>
                                <i class="el-icon-warning-outline" slot="reference"
                                    style="line-height: 40px;margin-left: 15px;"></i>
                            </el-popover>
                        </el-col>
                        <el-col :span="11">

                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="11">
                            <span class="span_item">
                                <span style="font-weight: 700;">分组池</span>
                            </span>
                        </el-col>

                        <el-col :span="11">
                            <el-form-item label="样品池" prop="name" style="padding-left: 65px;">
                                <el-input v-model="ruleForm.sample" @input="searchItem">
                                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                                </el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="2">
                            <div class="all_select" style="line-height: 40px;margin-left: 10px; cursor: pointer !important;"
                                @click="allAddItem">
                                <i class="el-icon-success themeTopToolColor"></i>
                                <span>全选</span>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="4">
                            <div class="group_left">
                                <div v-for="(item, index) in groupList" :key="index" class="group_left_item"
                                    :class="{ is_active: itemShow === index }" @click="itemShow = index"
                                    @mouseover="editIsShow = index" @mouseleave="editIsShow = null">
                                    <el-checkbox v-model="item.ischecked"
                                        @change="changeItemStatus($event, index)"></el-checkbox>
                                    <span class="group_left_item_content">{{ item.title }}</span>
                                    <el-popover placement="right" width="150" trigger="click" ref="popoverDom">
                                        <div>
                                            <el-input size="small" v-model="groupItemName"></el-input>
                                        </div>
                                        <div style="margin-top: 10px;">
                                            <el-button type="primary" size="mini" class="themeTopToolbgColor"
                                                @click="verify(index)"
                                                style="width: 56px;height: 28px;border-radius: 0;">确定</el-button>
                                            <el-button size="mini" @click="cancel">取消</el-button>
                                        </div>
                                        <el-tooltip class="item" effect="dark" content="重命名" placement="top"
                                            slot="reference" style="margin-right: 12px;">
                                            <i class="el-icon-edit group_left_item_edit" v-show="editIsShow === index"
                                                @click="editGroupItem(index)"></i>
                                        </el-tooltip>
                                    </el-popover>

                                </div>
                            </div>
                        </el-col>
                        <el-col :span="9">
                            <div class="group_middle">
                                <template v-if="groupList.length && groupList[itemShow]">
                                    <div v-for="(item, index) in groupList[itemShow].content" :key="index"
                                        class="group_middle_item" @mouseover="deleteShow = index"
                                        @mouseleave="deleteShow = null">
                                        <el-tooltip placement="top">
                                            <div slot="content">{{ item }}</div>
                                            <span>{{ item }}</span>
                                        </el-tooltip>
                                        <i class="el-icon-delete" v-show="deleteShow == index"
                                            @click="deleteItem(item, index)"></i>
                                    </div>
                                </template>
                            </div>
                        </el-col>
                        <el-col :span="11">
                            <div class="group_right">
                                <template v-for="(item, index) in sampleList">
                                    <el-tooltip placement="top">
                                        <div slot="content">{{ item }}</div>
                                        <div class="group_right_item" @click="addItem(item, index)">{{ item }}</div>
                                    </el-tooltip>
                                </template>
                            </div>
                        </el-col>
                    </el-row>
                    <div class="group_btn">
                        <div class="group_btn_left">
                            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
                                @change="changeStatus"></el-checkbox>
                            <el-button icon="el-icon-delete" size="mini" :disabled="!checkAll && !isIndeterminate"
                                @click="delItem">删除</el-button>
                            <el-popover placement="right" width="400" trigger="click">
                                <el-input type="textarea" :rows="12" placeholder="请输入内容" v-model="textareaList">
                                </el-input>
                                <el-button size="mini" type="primary" style="float:right;margin-top:5px"
                                    @click="customGroup">确定</el-button>
                                <el-button icon="el-icon-edit" size="mini" slot="reference">批量修改</el-button>
                            </el-popover>

                            <el-button icon="el-icon-refresh-left" size="mini" @click="cancelList">撤销修改</el-button>
                        </div>
                        <div class="group_btn_right">
                            <el-button type="primary" size="mini" class="themeTopToolbgColor" @click="verifyDialog"
                                style="width: 44px;height: 32px;border-radius: 0;">确认</el-button>
                            <el-button size="mini" @click="cancelDialog">取消</el-button>
                        </div>
                    </div>
                </el-form>
            </div>
        </el-dialog>
        <!-- 分组dom -->
        <div class="main_title">
            编辑分组
            <el-tooltip class="item" effect="dark" content="分组调整" placement="top">
                <i class="el-icon-edit edit_button" @click="openDialog"></i>
            </el-tooltip>
        </div>

        <div class="group_items_div">
            <template v-for="(item, index) in dataList">
                <el-popover placement="bottom" trigger="hover" width="195" popper-class="my_popover_style">
                    <div class="group_childrens">
                        <template v-for="(i, y) in item.content">
                            <el-tooltip placement="top">
                                <div slot="content">{{ i.title }}</div>
                                <div class="group_children" :class="{ 'is_active': i.ischecked }"
                                    @click="changeChildStatus(i, item)">{{ i.title }}
                                </div>
                            </el-tooltip>
                        </template>
                    </div>

                    <div class="items" :class="{ 'is_active': item.ischecked }" @click="changeStatusItem(item)"
                        slot="reference">{{ item.groupTitle }}
                    </div>
                </el-popover>
            </template>
        </div>
    </div>
</template>

<script>
import { compareGroupRequest } from '@/api/tools'
import { deepClone } from '@/utils';
export default {
    name: 'GenecloudUiChartAdjust',
    data() {
        let validate2 = (rule, value, callback) => {
            const index = this.groupList.findIndex(item => item.title == this.ruleForm.groupTool)
            if (index !== -1) {
                this.isDisabled = true
                callback(new Error("分组名已存在"));
            } else if (!/^[a-zA-Z]+([a-zA-Z_0-9]+)?$/.test(value)) {
                this.isDisabled = true
                callback(new Error("格式错误！"));
            } else if (value.length > 8 || value.length < 1) {
                this.isDisabled = true
                callback(new Error("格式错误！"));
            } else {
                this.isDisabled = false
                callback();
            }
        }
        return {
            //分组信息
            dataList: [],
            dialogVisible: false,
            groupDialogWidth: '800px',
            groupObject: {},
            ruleForm: {
                groupTool: '',
                option: '',
                sample: ''
            },
            //重命名标签
            editIsShow: null,
            //选中的menu
            itemShow: 0,
            //全选
            isIndeterminate: false,
            checkAll: '',
            //样品池
            result: [],
            sampleList: [],
            //分组池
            isDisabled: true,
            groupList: [],
            deleteShow: null,
            groupItemName: '',
            rules: {
                groupTool: [
                    { required: true, validator: validate2, trigger: ['change'] },
                ]
            },
            textareaList: '',
            judgment: null,
        };
    },
    watch: {
        '$attrs.option': {
            handler(val, newVal) {
                if (val) {
                    this.dataList = deepClone(val.group.dataGroupList)
                    this.groupObject = deepClone(val.group)
                    this.init(val.group)
                }
            },
            immediate: true,
            deep: true
        }
    },
    created() {
        let type = this.$attrs.option.legendConfig.reduce((pre, item, index) => {
            item.config.forEach(i => {
                pre.push(i.type)
            })
            return pre
        }, [])
        if (type.includes('mutualExclusion')) {
            this.judgment = true
        } else {
            this.judgment = false
        }
    },
    mounted() {

    },
    methods: {
        openDialog() {
            this.dialogVisible = true
        },
        //改变分组状态
        changeStatusItem(value) {
            if (value.ischecked) {
                let num = 0
                this.dataList.forEach(item => {
                    if (item.ischecked) {
                        num++
                    }
                })
                if (this.judgment) {
                    if (num < 3) return this.$message.error('至少需要存在2个分组！')
                } else {
                    if (num < 2) return this.$message.error('至少需要存在1个分组！')
                }
            }
            value.ischecked = !value.ischecked
            if (!value.ischecked) {
                value.content.map(item => {
                    item.ischecked = false
                })
            } else {
                value.content.map(item => {
                    item.ischecked = true
                })
            }
            this.$emit('changeStatus', this.dataList)
        },
        //改变分组子级状态
        changeChildStatus(i, list) {
            if (i.ischecked) {
                let num = 0
                list.content.forEach(item => {
                    if (item.ischecked) {
                        num++
                    }
                })
                if (num < 3) return this.$message.error('每种分组至少需要存在2个样本！')
            }
            i.ischecked = !i.ischecked
            const flag = list.content.every(item => !item.ischecked)
            if (flag) {
                list.ischecked = false
            } else {
                list.ischecked = true
            }
            this.$emit('changeStatus', this.dataList)
        },
        changeGroupList({ dataGroupList, sampleList }) {
            this.dialogVisible = false
            this.dataList = dataGroupList
            this.groupObject.dataGroupList = dataGroupList
            this.groupObject.sampleList = sampleList
        },
        init({ dataGroupList, sampleList }) {
            if (Boolean(dataGroupList.length)) {
                this.groupList = dataGroupList.reduce((pre, item, index) => {
                    pre.push({
                        title: item.groupTitle,
                        ischecked: false,
                        content: item.content.map(i => i.title)
                    })
                    return pre
                }, [])
                this.sampleList = deepClone(sampleList)
                this.result = dataGroupList.reduce((pre, item, index) => {
                    let arr = item.content.map(i => i.title)
                    pre.push(...arr)
                    return pre
                }, []).concat(this.sampleList)

            } else {
                this.groupList = []
                this.sampleList = deepClone(sampleList)
            }
        },
        //撤销修改
        cancelList() {
            let cancelObject = JSON.parse(localStorage.getItem(this.$router.history.current.name))
            // console.log(this.cancelObject,'cancelObject');
            this.init(cancelObject)
        },
        addGroup() {
            this.groupList.push(
                {
                    title: this.ruleForm.groupTool,
                    content: [],
                    ischecked: false
                }
            )
            this.ruleForm.groupTool = ''
        },
        addItem(item, index) {
            if (this.groupList.length > 0) {
                this.groupList[this.itemShow].content.push(item)
                this.sampleList.splice(index, 1)
            }
        },
        allAddItem() {
            if (this.groupList.length > 0) {
                // this.sampleList.forEach((item, index) => {
                this.groupList[this.itemShow].content.push(...this.sampleList)
                this.sampleList.splice(0, this.sampleList.length)
                // })
            }
        },
        //反选
        changeItemStatus(value, index) {
            this.groupList[index].ischecked = value
            const isAll = this.groupList.every(item => item.ischecked)
            this.checkAll = isAll
            this.isIndeterminate = isAll ? false : true
        },
        //全选功能
        changeStatus() {
            this.groupList.map(item => item.ischecked = this.checkAll)
            this.isIndeterminate = false;
        },
        //删除分组池内容
        delItem() {
            const item = this.groupList.reduce((pre, item, index) => {
                if (item.ischecked) {
                    pre.push(...item.content)
                }
                return pre
            }, [])
            this.sampleList.push(...item)
            this.groupList = this.groupList.filter(item => !item.ischecked)
            if (this.groupList.length <= 0) {
                this.checkAll = false
            }
        },
        //重命名
        editGroupItem(index) {
            this.groupItemName = this.groupList[index].title
        },
        //确定
        verify(index) {
            const a = this.groupList.find(i => i.title === this.groupItemName)
            const b = this.groupList.findIndex(i => i.title === this.groupItemName)
            if (a && b !== index) return this.$message.error('分组名重复！')
            document.body.click()
            this.groupList[index].title = this.groupItemName
        },
        //取消
        cancel() {
            document.body.click()
        },
        //筛选
        searchItem() {
            let groupItems = []
            let filterList = []
            this.groupList.forEach(item => {
                groupItems = groupItems.concat(item.content)
            })
            filterList = this.result.reduce((pre, item, index) => {
                if (!groupItems.includes(item)) {
                    pre.push(item)
                }
                return pre
            }, [])
            if (!this.ruleForm.sample) {
                this.sampleList = filterList
            } else {
                this.sampleList = filterList.filter(item => item.includes(this.ruleForm.sample))
            }
        },
        //删除
        deleteItem(item, index) {
            this.sampleList.push(item)
            this.groupList[this.itemShow].content.splice(index, 1)
        },
        //确认分组条件
        verifyDialog() {
            let arr = this.groupList.reduce((pre, item, index) => {
                let content = item.content.map(i => {
                    return { ischecked: true, title: i }
                })
                pre.push({
                    ischecked: true,
                    groupTitle: item.title,
                    content
                })
                return pre
            }, [])
            if (arr.length < 1) return this.$message.error('至少需要存在一种分组！')
            this.changeGroupList({ dataGroupList: arr, sampleList: this.sampleList })
            this.$emit('changeGroupList', { dataGroupList: arr, sampleList: this.sampleList })
        },
        cancelDialog() {
            this.init(this.groupObject)
            this.dialogVisible = false
        },
        //根据分组调整
        changeGroup(value) {
            const { groupItems, groupList } = value
            this.sampleList = groupList
            this.result = groupList
            this.groupList = groupItems
        },
        async customGroup() {
            //this.cancelObject 原始数据
            //this.textareaList 输入文本
            let fileId = JSON.parse(localStorage.getItem(this.$router.history.current.name + 'taskId')) || "demo"
            let pageCode = this.$router.history.current.name
            const res = await compareGroupRequest({
                fileId,
                pageCode,
                text: this.textareaList
            })
            if (res.code !== 200) return this.$message.error(res.message)
            if (res.message) {
                this.$confirm(`${res.message},是否继续操作？`, '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                    beforeClose: async (action, instance, done) => {
                        if (action === 'confirm') {
                            this.init(res.data)
                            this.textareaList = ''
                        } else if (action === 'cancel') {
                            this.$message({
                                message: '取消操作',
                            })
                            this.textareaList = ''
                        }
                        done();
                    }
                }).catch(() => { })
            } else {
                this.init(res.data)
                this.textareaList = ''
                document.body.click()
            }
        }
    },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.themeTopToolbgColor {
    background-color: $themeTopToolColor;
    border: 0;
    color: #fff;
    width: 90px;
    height: 38px;
    border-radius: 19px;
}

.adjust_from {
    padding: 20px 0;

    ::v-deep .el-input__inner {
        height: 35px;
        border-radius: 6px;
    }

    .top_item {
        ::v-deep .el-input__inner {
            border-radius: 0 6px 6px 0;
        }
    }

    ::v-deep .el-button--mini {
        padding: 9px;
        margin-left: 10px;
    }

    ::v-deep .el-select-dropdown__item {
        .select_i {
            &:hover {
                color: red !important;
            }
        }

    }

    ::v-deep .el-dialog__header {
        text-align: center;
        font-weight: 700;
        border-bottom: 1px solid #ccc;
    }

    ::v-deep .el-input-group__prepend {
        padding: 0 8px;
    }

    ::v-deep .el-radio {
        margin-right: 5px;
    }

    .group_items_div {
        display: flex;
        align-content: flex-start;
        flex-wrap: wrap;
        justify-content: flex-start;
        padding: 25px 0 25px 30px;
        width: 100%;
        // height: 200px;
        // overflow-y: auto;

        .items {
            width: 74px;
            height: 30px;
            text-align: center;
            line-height: 26px;
            margin: 0 10px 10px 0;
            background-color: #fff;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            border: 1px solid #ccc;
            color: #666;
            border-radius: 3px;
            cursor: pointer;

            &.is_active {
                border: 2px solid $themeTopToolColor;
            }
        }
    }
}

.my_popover_style {
    .group_childrens {
        display: flex;
        flex-wrap: wrap;
        align-content: flex-start;
        width: 220px;
        margin: 0 auto;
        max-height: 300px;
        overflow-y: auto;

        .group_children {
            width: 50px;
            overflow: hidden;
            text-overflow: ellipsis;
            text-wrap: nowrap;
            margin: 0 8px 8px 0;
            height: 24px;
            text-align: center;
            line-height: 24px;
            border: 1px solid #ccc;
            cursor: pointer;

            // &:nth-child(3n) {
            //     margin: 0;
            // }

            &.is_active {
                border: 1px solid $themeTopToolColor;
            }
        }
    }
}

.main_title {
    font-size: 14px;
    color: #333;
    font-weight: 700;
}

.edit_button {
    cursor: pointer;
    width: 30px;
    height: 30px;
    text-align: center;
    line-height: 30px;

    &:hover {
        background-color: #ccc;
        border-radius: 50%;
    }
}


.themeTopToolbgColor {
    background-color: $themeTopToolColor;
    border: 0;
}

.themeTopToolColor {
    color: $themeTopToolColor;
}

.dialog_content {
    .span_item {
        line-height: 40px;
    }

    // .el-form-item{
    //     margin: 0;
    // } 

    .group_item {
        position: relative;

        ::v-deep .el-input__inner {
            border-radius: 6px 0 0 6px;

        }
    }

    .group_left,
    .group_right,
    .group_middle {
        height: 300px;
        border: 1px solid #ccc;
        overflow-y: auto;
    }

    .group_middle {
        border-left: 0;
    }


    .group_left {
        display: flex;
        flex-direction: column;
        padding: 15px 0;

        .group_left_item {

            cursor: pointer;
            display: flex;
            justify-content: space-around;
            width: 100%;
            padding: 6px 15px;

            &:hover {
                background-color: #eaf6ff;
            }

            .group_left_item_content {
                width: 100%;
                padding: 0 5px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            .popover_btn {
                padding-top: 10px;
            }

            &.is_active {
                color: $themeTopToolColor;
                background-color: #e9f6ff;
            }
        }
    }

    .group_middle {
        display: flex;
        flex-wrap: wrap;
        align-content: flex-start;
        padding: 15px;

        .group_middle_item {
            display: flex;
            align-items: center;
            text-align: center;
            cursor: pointer;
            width: 72px;
            height: 32px;
            line-height: 32px;
            margin: 0 10px 10px 0;
            background-color: #eae9e9;

            &:nth-child(3n) {
                margin-right: 0;
            }

            span {
                padding-right: 10px;
                width: 60px;
                overflow: hidden;
                text-overflow: ellipsis;
                text-wrap: nowrap;
            }

            &:hover {
                background-color: #eaf6ff;
                color: $themeTopToolColor;
            }

        }
    }

    .group_right {
        margin-left: 25px;
        display: flex;
        flex-wrap: wrap;
        align-content: flex-start;
        padding: 15px;

        .group_right_item {
            text-align: center;
            cursor: pointer;
            width: 75px;
            overflow: hidden;
            text-wrap: nowrap;
            text-overflow: ellipsis;
            height: 32px;
            line-height: 32px;
            margin: 0 10px 10px 0;
            background-color: #eae9e9;

            &:hover {
                background-color: #eaf6ff;
                color: $themeTopToolColor;
            }

            &:nth-child(3n) {
                margin-right: 0;
            }

        }
    }

    .group_btn {
        margin-top: 15px;
        display: flex;
        justify-content: space-between;
    }
}
</style>